/*
 Copyright 2009 Christian Sprecher

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
 */

package helpers

import ca.odell.glazedlists.gui.WritableTableFormat
import javax.jcr.PropertyType
import ca.odell.glazedlists.gui.TableFormat
import javax.jcr.Session

/**
 * JcrProperties consist of
 * name (editable?)
 * value (editable per value type)
 * value type (readonly)
 */


class JcrPropertiesTableFormat implements TableFormat{
    def columnNames = ["Name", "Type", "Value"]
    JcrHelper helper
    public JcrPropertiesTableFormat(Session session) {
        helper = new JcrHelper(session)
    }
    def valueDisplayerDispatcher = {  property ->
        if(!property) return
        def result
        if(property.definition.isMultiple()) return "multiple values"
        switch(property.type) {
            case PropertyType.BINARY:
                result = "binary value"
                break
            case PropertyType.BOOLEAN:
                result = property.getBoolean()
                break
            case PropertyType.DATE:
                result = property.getDate()
                break;
            case PropertyType.DOUBLE:
                result = property.getDouble()
                break;
            case PropertyType.LONG:
                result = property.getLong()
                break;
//fall through to default
            case PropertyType.NAME:
            case PropertyType.PATH:
            case PropertyType.REFERENCE:
            case PropertyType.STRING:
            default:
                result = property.getString()
        }
        result
    }
    
    def columnValueHandler = [{it?.name}, {PropertyType.nameFromValue(it?.type)}, {valueDisplayerDispatcher(it)}]


    public int getColumnCount() {
        return columnNames.size  //To change body of implemented methods use File | Settings | File Templates.
    }

    public String getColumnName(int i) {
        return columnNames[i]
    }

    public Object getColumnValue(Object propertyPath, int i) {
        return helper.withProperty(propertyPath) {property -> columnValueHandler[i](property)}
    }

/*
    public boolean isEditable(Object e, int i) {
        return i==2;  //To change body of implemented methods use File | Settings | File Templates.
    }

    public Object setColumnValue(Object e, Object o, int i) {
        println "setting col value"
        return e;  //To change body of implemented methods use File | Settings | File Templates.
    }
    */
}
